package MyArray;

public class sumOfDiagonal {
    public static int sumOfDiagonal(int[][] a){
        // 例题4.4
        int i=0;
        int n= a[0].length;
        int sum1=0;
        int sum2=0;
        int sum;

        for(i=0; i<a.length; i++){
            // 主对角线
            sum1 += a[i][i];
            // 副对角线
            sum2 += a[i][n-i-1];
        }
        sum = sum1 + sum2;
        // 当矩阵行数为奇数时，减去两条对角线相交的元素
        if(n%2==1){
            sum -= a[n/2][n/2];
        }
        return sum;
    }

    public static void main(String[] args) {
        int[][] arr = new int[4][4];
        arr[0] =new int[] {23,65,43,68};
        arr[1] =new int[] {45,99,86,80};
        arr[2] =new int[] {76,81,34,45};
        arr[3] =new int[] {88,64,48,25};

        int value = sumOfDiagonal(arr);
        System.out.println(value);
    }


}
